package com.zyx.springmvcmsb.advanced.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;

/**
 * @author zyx
 * @since 2021/10/5 18:13
 */
@Controller
public class DownloadController {

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request) throws Exception {
        // 获取要下载的路径
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("scripts/jquery-1.9.1.min.js");
        System.out.println("realPath =====>>>>> " + realPath);
        // 通过io流对文件进行读写
        FileInputStream fis = new FileInputStream(realPath);
        byte[] bytes = new byte[fis.available()];
        fis.read(bytes);
        fis.close();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-Disposition", "attachment;filename=jquery-1.9.1.min.js");
        return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
    }

}
